package com.china.bike.controller;

import com.alibaba.fastjson.JSON;
import com.china.bike.dto.UserDto;
import com.china.bike.entity.BikeAccount;
import com.china.bike.entity.BikeRepairRecord;
import com.china.bike.entity.BikeUseRecord;
import com.china.bike.entity.User;
import com.china.bike.service.BikeAccountService;
import com.china.bike.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private BikeAccountService bikeAccountService;

    @RequestMapping(value = "/create-user", method = RequestMethod.POST)
    public void createUser(@RequestBody User user) {
        userService.createUser(user);
    }

    @RequestMapping(value = "/search-user", method = RequestMethod.POST)
    public UserDto searchUser(@RequestBody User user) {
        User searchUser = userService.searchUser(user);
        BikeAccount userAccount = bikeAccountService.getUserAccount(user.getId());

        String jsonString = JSON.toJSONString(searchUser);
        UserDto userDto = JSON.parseObject(jsonString, UserDto.class);
        userDto.setIsDeposit(userAccount.getIsDeposit());
        userDto.setDepositAmount(userAccount.getDepositAmount());
        userDto.setBalance(userAccount.getBalance());

        return userDto;
    }

    @RequestMapping(value = "/search-user-journey", method = RequestMethod.POST)
    public List<BikeUseRecord> searchUserJourney(HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        return userService.searchUserJourney(user);
    }

    @RequestMapping(value = "/search-bike-repair-record", method = RequestMethod.POST)
    public List<BikeRepairRecord> searchBikeRepairRecord(HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        return userService.searchBikeRepairRecord(user);
    }

    @RequestMapping(value = "/charge-money", method = RequestMethod.POST)
    public void chargeMoney(@RequestParam(value = "charge") BigDecimal charge, HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        bikeAccountService.chargeMoney(charge, user);
    }

}
